from collections import Counter
import requests
import datetime

PHONE_NUMBERS = {"熊凤婷": "19122737581", "聂钰铰": "15023557548", "陈梦圆": "18723530812", "谭超": "18183123378",
                 "蒋娇": "18875259733", "文瑞丰": "13368036672"}


def count_case(msg):
    """
    :param msg: 来自metersphere的消息
    :return: 拼接后的消息内容和@的手机号
    """
    a = msg.split('=')[1]
    # 测试报告连接
    u = "https://meters.officemate.cn/track/share-plan-report?shareId=" + a
    # 获取关键数据
    b = requests.get(f'https://meters.officemate.cn/track/share/info/get/{a}').json()['data']['customData']
    c = requests.get(f"https://meters.officemate.cn/track/share/test/plan/report/db/{a}/{b}").json()
    # 结束时间
    end_time = datetime.datetime.fromtimestamp(int(c["data"]["endTime"] / 1000))
    # 通过率
    pass_rate= c['data']["passRate"]
    # 用例总数
    all_case_num = c['data']['caseCount']
    if len(c['data']['apiResult']['apiScenarioData']) == 1:  # 全部成功
        # 成功用例数
        success_case_num = c['data']['apiResult']['apiScenarioData'][0]['count']
        # 失败用例数
        failed_case_num = 0
    else:  # 有失败
        success_case_num = [d['count'] for d in c['data']['apiResult']['apiScenarioData'] if d['status'] == "SUCCESS"][0]
        failed_case_num = [d['count'] for d in c['data']['apiResult']['apiScenarioData'] if d['status'] == "ERROR"][0]

    if failed_case_num:
        name_counts = Counter(d['creatorName'] for d in c["data"]["scenarioFailureCases"])
        # @的人员手机号列表
        at_numbers = [PHONE_NUMBERS[i] for i in name_counts.keys()]
        # @的人员手机号字符串
        at_str = ''
        for s in at_numbers:
            at_str = at_str + "@" + s
        markdown_text = f"""
## 自动化测试报告  \n\n  
【执行时间】:{end_time}  \n\n  
【用例总数】: **{all_case_num}**  \n\n  
【成功用例】: <font color='#51a689'>**{success_case_num}**</font>  \n\n  
【失败用例】: <font color='#c55c6b'>**{failed_case_num}**</font>  \n\n  
【成功率】:  <font color='#51a689'>**{round(pass_rate * 100, 2)}%**</font>  \n\n  
👉[查看详情]({u})  \n\n  
{''.join([f"{name}: <font color='#FF4500'>{count}</font> " for name, count in name_counts.items()])}  \n\n  
{at_str}
"""
    else:
        markdown_text = f"""
## 自动化测试报告  \n\n  
【执行时间】:{end_time}  \n\n  
【用例总数】: **{all_case_num}**  \n\n  
【成功用例】: <font color='#51a689'>**{success_case_num}**</font>  \n\n  
【失败用例】: <font color='#c55c6b'>**{failed_case_num}**</font>  \n\n  
【成功率】:  <font color='#51a689'>**{pass_rate * 100}%**</font>  \n\n  
👉[查看详情]({u})  \n\n  
"""
        at_numbers = []
    return markdown_text, at_numbers
